package com.boot.base.web;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Component
public class UploadCompont {


    /**
     * @param restTemplate
     * @param url 目标url
     * @param title 名称
     * @param device 设备类型
     * @param sport <option value="3" _v-8291874c="">骑车</option> <option value="2" _v-8291874c="">跑步</option> <option value="4" _v-8291874c="">徒步</option> <option value="0" _v-8291874c="">自由行</option> <option value="8" _v-8291874c="">室内训练</option>
     * @param path 文件在本地位置
     * @return
     */
    public String xinzheupload(RestTemplate restTemplate, String url, String title, Integer device, Integer sport, String path, String cookie) {
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        headers.add("Cookie",cookie);

        //设置请求体，注意是LinkedMultiValueMap
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("title", title);
        form.add("device", device);
        form.add("sport", sport);
        form.add("upload_file_name", new FileSystemResource(path));

        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

        String res=null;
        try {
            res=restTemplate.postForObject(url, files, String.class);
        } catch (RestClientException e) {
//            e.printStackTrace();
        }
        return res;
    }
}
